package personal.zq.practice.common.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import personal.zq.practice.common.bo.DownloadFileResp;

@Slf4j
public class HttpDownloadUtils {
    private HttpDownloadUtils() {
    }

    /**
     * 使用url下载文件，返回byte[]
     *
     * <p>
     * 不建议下载大文件
     * </p>
     *
     * @param imgUrl 文件路径
     * @return
     */
    public static DownloadFileResp download(String imgUrl) {
        byte[] data;
        InputStream in = null;
        DownloadFileResp resp = new DownloadFileResp();
        String validUrl = ESAPIUtil.getValidUrl(imgUrl);
        // 过
        HttpGet httpGet = new HttpGet(validUrl);
        try (ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
             CloseableHttpClient httpClient = HttpClientBuilder.create().build();
             CloseableHttpResponse closeableHttpResponse = httpClient.execute(httpGet)) {

            HttpEntity entity = closeableHttpResponse.getEntity();
            Header contentType = entity.getContentType();
            // 获取文件类型
            resp.setContentType(contentType.getValue());

            StatusLine statusLine = closeableHttpResponse.getStatusLine();
            if (statusLine != null && statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
                // 中间流
                in = entity.getContent();
                byte[] buff = new byte[1024];
                int rc;
                while ((rc = in.read(buff, 0, buff.length)) > 0) {
                    swapStream.write(buff, 0, rc);
                }
                data = swapStream.toByteArray();
                resp.setContent(data);
            }
        } catch (IOException e) {
            log.error(" 获取网络资源失败，imgUrl ={}", imgUrl, e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.error(" 流关闭失败", e);
                }
            }
        }
        return resp;
    }
}
